<?php
namespace Common\Models;
use Common\BaseModel;
use Common\Common;

class WOrderSettle extends BaseModel
{
    public $res;
    public $expire;
    public function initialize()
    {
        parent::initialize();
        $this->setSource('w_union_order');
    }


    /**
     * 订单插入到用户订单表
     */
    public function insertUpdateUnionUserOrder($column, $data)
    {
        $FUsersExtend = new FUsersExtend();
        $ridToUserIdChannelId = $FUsersExtend->ridMappingUserId($column, array_column($data, 'rid'));

        $databaseOrder = $this->orderNoDb($data);           //数据库中存在的订单
        $WAPlatform = new WAPlatform();
        $revenuesRateDi = $WAPlatform->getGroupList();
        foreach ($data as $key => $value) {
//            $user_id = isset($ridToUserIdChannelId[$value['rid']]['user_id']) ? $ridToUserIdChannelId[$value['rid']]['user_id'] : 0;
            $revenuesAmount = $this->revenuesRate($value['rebateAmount'], $value['orderSrc'], $revenuesRateDi);      //获取扣税

            if (isset($databaseOrder[$value['orderId']])) {           //存在订单
                $issetOrder = $this->updateOrderBean($databaseOrder[$value['orderId']], $value, $ridToUserIdChannelId);
                if ($issetOrder) {
                    $responseResult = $this->findFirst("order_id='{$value['orderId']}'");

                    $responseResult->user_id = isset($ridToUserIdChannelId[$value['rid']]['user_id']) ? $ridToUserIdChannelId[$value['rid']]['user_id'] : 0;
                    $responseResult->pay_money = $value['payMoney'];
                    if (!in_array($value['orderStatus'], [3, 5, 11]) && in_array($issetOrder, [1, 5])) {  //失效订单 或 原始佣金和佣金金额没有发生变化则不更新订单佣金 订单有效
                        $responseResult->original_commission = $value['rebateAmount'];
                        $responseResult->income_rate = $revenuesAmount['revenues'];                         //后台当前设置的税金比例
                        $responseResult->commition_rate = $revenuesAmount['tax_amount'];                              //扣税之后的金额
                        $responseResult->commition = $revenuesAmount['income_amount'];        //扣税之后结算给用户的金额
                    }
                    $responseResult->order_status = ($value['orderType'] == 3 || in_array($databaseOrder[$value['orderId']]['order_type'], [2, 3, 4, 5])) ? $databaseOrder[$value['orderId']]['order_status'] : $value['orderStatus'];
                    $responseResult->updated = date("Y-m-d H:i:s");
                    $responseResult->order_paid_time = $value['orderPaidTime'];
                    $responseResult->order_earning_time = $value['orderEarningTime'];
                    if ($databaseOrder[$value['orderId']]['order_type'] == 3 || (isset($value['isPunish']) && $value['isPunish'])) {       //违规订单
                        $value['orderType'] = 3;
                    }
                    $responseResult->order_type = in_array($databaseOrder[$value['orderId']]['order_type'], [2,3,4]) ? $databaseOrder[$value['orderId']]['order_type'] : $value['orderType'];   //订单是违规和维权订单，不改变原来的属性
                    $responseResult->is_update = 1;

                    if ($responseResult->commition > 0 && $responseResult->user_id != 0) {
                        $responseResult->is_update = 1;
                    }

                    if ($responseResult->save()) {
                        var_dump("更新成功{$value['orderId']}");
                    } else {
                        var_dump("更新失败{$value['orderId']}");
                    }
                }
            } else {
                $WOrderSettleDb = new WOrderSettle();
                $WOrderSettleDb->user_id = isset($ridToUserIdChannelId[$value['rid']]['user_id']) ? $ridToUserIdChannelId[$value['rid']]['user_id'] : 0;
                $WOrderSettleDb->order_id = $value['orderId'];
                $WOrderSettleDb->order_status = $value['orderStatus'];
                $WOrderSettleDb->goods_name = $value['name'];
                $WOrderSettleDb->goods_id = $value['goodsId'];
                if ($value['images']) {
                    $value['images'] = strpos($value['images'], 'http') !== false ? $value['images'] : "https:{$value['images']}";
                } else {
                    $value['images'] = "";
                }
                $WOrderSettleDb->goods_pic = $value['images'];
                $WOrderSettleDb->site = $value['site'];
                $WOrderSettleDb->item_site = $value['orderSrc'];
                $WOrderSettleDb->tag = $value['tagItem'];
                $WOrderSettleDb->shop_name = isset($value['shopName']) ? $value['shopName'] : $value['shopName'];
                $WOrderSettleDb->rid = $value['rid'];
                $WOrderSettleDb->price = $value['price'];
                $WOrderSettleDb->pay_money = $value['payMoney'];
                $WOrderSettleDb->original_commission = $value['rebateAmount'];
                $WOrderSettleDb->income_rate = $revenuesAmount['revenues'];                         //后台当前设置的税金比例
                $WOrderSettleDb->commition_rate = $revenuesAmount['tax_amount'];                              //扣税之后的金额
                $WOrderSettleDb->commition = $revenuesAmount['income_amount'];        //扣税之后结算给用户的金额
                $WOrderSettleDb->order_create_time = $value['orderCreateTime'];
                $WOrderSettleDb->order_paid_time = $value['orderPaidTime'];
                $WOrderSettleDb->order_earning_time = $value['orderEarningTime'];
                $WOrderSettleDb->created = date("Y-m-d H:i:s");
                $WOrderSettleDb->updated = date("Y-m-d H:i:s");
                $WOrderSettleDb->order_type = $value['orderType'];
                //分佣
                if ($WOrderSettleDb->commition > 0 && $WOrderSettleDb->user_id != 0) {
                    $WOrderSettleDb->is_update = 1;
                }
                try {
                    if ($WOrderSettleDb->save()) {

                        if (isset($ridToUserIdChannelId[$value['rid']]['user_id']) && !empty($ridToUserIdChannelId[$value['rid']]['user_id']) && $value['payMoney'] > 1 && $value['orderStatus'] > 1) {
                            //有效用户 第一次下单记录

                        }
                        var_dump("插入成功{$value['orderId']}");
                    } else {
                        var_dump("插入失败{$value['orderId']}");
                    }
                } catch (\Exception $e) {
                    var_dump($e->getMessage(), $value);
                }
            }
        }
        return true;
    }





    /**
     * 通过订单号集合查找订单
     */
    public function orderNoDb($orderNoArr)
    {

        $orderNoArray = array_column($orderNoArr, 'orderId');
        $orderIds = "'" . join("','", array_values($orderNoArray) ) . "'";
        $conditions = "order_id in({$orderIds})";
        $orderListArr = $this->find(
            array(
                $conditions,
            )
        )->toarray();
        if ($orderListArr) {
            $responseResult = [];
            foreach ($orderListArr as $key => $value) {
                $responseResult[$value['order_id']] = $value;
            }
            return $responseResult;
        } else {
            return [];
        }
    }


    /**
     * 扣税比例
     * @param $commition    第三方回来的订单佣金
     * @param $src      平台 1.淘宝 2.京东 3.拼多多 4.唯品会 5.苏宁 6美团
     * @param $revenues 每个平台的税金比例
     */
    public function revenuesRate($commition, $src, $revenues)
    {
        //revenues  扣手续费比例 tax_amount 扣税金额 income_amount 用户可分的佣金
        $responseResult = ['revenues' => 0, 'tax_amount' => 0, 'income_amount' => 0];

        if(isset($revenues[$src])){
            $responseResult['revenues'] = $revenues[$src]['technicalService'];
            $technicalService = Common::bc($revenues[$src]['technicalService'],'100','/');
            $responseResult['tax_amount'] =Common::bc($commition,$technicalService,'*');
            $responseResult['income_amount'] = Common::bc($commition,$responseResult['tax_amount'],'-');
        }
        return $responseResult;
    }




    /**
     * 更新的时候判断 第三方回来的佣金是否和库里面的佣金相同
     */
    public function updateOrderBean($databaseData, $platment, $ridToUserIdChannelId = [])
    {//1122
        $commition = Common::bc($platment['rebateAmount'], "0", "+");
        if ($commition != $databaseData['original_commission']) {        //佣金金额不一样
            return 1;
        }

        $payMoney = Common::bc($platment['payMoney'], "0", "+");
        if ($payMoney != $databaseData['pay_money']) {         //交易金额
            return 2;
        }

        if ($platment['orderStatus'] != $databaseData['order_status']) {  //订单状态
            return 3;
        }

        if (isset($ridToUserIdChannelId[$platment['rid']]['user_id']) && $ridToUserIdChannelId[$platment['rid']]['user_id']) {        //数据库用户发生变化
            if ($databaseData['user_id'] != $ridToUserIdChannelId[$platment['rid']]['user_id']) {
                return 5;
            }
        }

        return 0;
    }





}
